import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/common_search/bean/event_bus_search_result.dart';
import 'package:dk_flutter_module_sale/common/common_search/widget/widget_common_search_bar.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'page_house_source_home.dart';

class TabChangeContentEvent {
  String searchContent;
  TabChangeContentEvent(this.searchContent);
}

@ARoute(url: CommonWidgetRoute.COMMON_GOAL_HOUSE_SOURCE_LIST)
class PageGoalHouseSource extends CommonPageWithTrack {
  final BoostRouteOption option;
  PageGoalHouseSource(this.option) : super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("收房-目标房源-列表", null);
  }

  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    pageBloc.switchPage(GoalHouseSourceWidget(pageBloc));
  }
}

// ignore: must_be_immutable
class GoalHouseSourceWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  GoalHouseSourceWidget(this.pageBloc);
  @override
  GoalHouseSourceState createState() {
    return GoalHouseSourceState(this.pageBloc);
  }
}

class GoalHouseSourceState extends State<GoalHouseSourceWidget>
    with SingleTickerProviderStateMixin {
  CommonPageBloc pageBloc;
  final EventBus searchEventBus = EventBus();

  // tab页
  var _index = 0;
  var _isPageCanChanged = true;
  TabController _tabController;
  PageController _pageController = PageController(initialPage: 0);

  //搜索的关键字
  String searchContent = "";

  GoalHouseSourceState(this.pageBloc);
  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 3, vsync: this);
    pageBloc.eventBus
        ?.on<SearchResultEvent>()
        ?.listen((SearchResultEvent event) {
      if (searchContent == event.content) return;
      setState(() {
        searchContent = event.content;
      });
      searchEventBus.fire(TabChangeContentEvent(event.content));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DkAppBar(DKAppBarParams.withBackNoMenu(pageBloc.context,
          titleContent: "目标房源列表")),
      backgroundColor: Color(0XFFF7F8F9),
      resizeToAvoidBottomPadding: true,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          CommonSearchBar(
            pageBloc.eventBus,
            initContent: "",
            placeHolder: "请输入小区名",
            isShowCancel: false,
            isSafeArea: false,
            returnKeyDownKeyBoard: true,
          ),
          Container(
            height: 44,
            color: Colors.white,
            child: TabBar(
              onTap: (index) {
                if (!mounted) {
                  return;
                }
                _pageController.jumpToPage(index);
              },
              isScrollable: false,
              controller: _tabController,
              labelStyle: const TextStyle(
                fontSize: 14.0,
                color: Color(0xff3DBCC6),
                fontWeight: FontWeight.normal,
              ),
              unselectedLabelStyle: const TextStyle(
                  fontSize: 14.0,
                  color: Color(0xff666666),
                  fontWeight: FontWeight.normal),
              indicatorSize: TabBarIndicatorSize.label,
              indicatorColor: Color(0xff3DBCC6),
              indicatorWeight: 2,
              unselectedLabelColor: Color(0xff666666),
              labelColor: Color(0xff3DBCC6),
              //indicatorPadding: const EdgeInsets.only(left: 5.0, right: 5.0,bottom: 7),
              tabs: <Widget>[
                Tab(
                  text: "未完成",
                ),
                Tab(
                  text: "已获取房源",
                ),
                Tab(
                  text: "已关闭",
                )
              ],
            ),
          ),
          Container(
            height: 0.5,
            color: Color(0xffebebeb),
          ),
          Expanded(
            child: PageView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: 3,
              onPageChanged: (index) {
                if (_isPageCanChanged) {
                  //由于pageview切换是会回调这个方法,又会触发切换tabbar的操作,所以定义一个flag,控制pageview的回调
                  _onPageChange(index);
                }
              },
              controller: _pageController,
              itemBuilder: (BuildContext context, int index) {
                return getPageView(index);
              },
            ),
          )
        ],
      ),
    );
  }

  Widget getPageView(int index) {
    return PageHouseSourceHome(searchEventBus, index + 1, searchContent);
  }

  _onPageChange(int index, {PageController page, TabController t}) async {
    if (page != null) {
      _isPageCanChanged = false;
      await _pageController.animateToPage(index,
          duration: Duration(milliseconds: 300),
          curve: Curves.ease); //等待pageview切换完毕,再释放pageivew监听
      _isPageCanChanged = true;
    } else {
      FocusScope.of(context).requestFocus(FocusNode());
      _tabController.animateTo(index); //切换Tabbar
    }
    setState(() {
      _index = index;
    });
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }
}
